package com.think.admin.util;

import com.think.admin.model.dto.EnumDTO;
import com.think.common.enums.IEnum;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 枚举工具类
 * </p>
 *
 * @author: xwj
 * @data: 2019-06-25
 */
public class IEnumUtil {
    /**
     * 所有枚举对象的 map
     */
    public static final Map<String, List<EnumDTO>> ENUM_MAP = new HashMap<>(50);

    static {
        try {
            List<String> packageNames = new ArrayList<>();
            packageNames.add("com.think.common.enums");
            packageNames.add("com.think.dao.enums");
            packageNames.add("com.think.admin.enums");
            for (String packageName : packageNames) {
                List<String> classNames = PackageUtil.getClassName(packageName);
                if (classNames != null) {
                    for (String classname : classNames) {
                        Class cls = Class.forName(classname);
                        if (IEnum.class.isAssignableFrom(cls) && cls.isEnum()) {
                            Method method = cls.getMethod("values");
                            IEnum[] iEnums = (IEnum[]) method.invoke(null, null);
                            List<EnumDTO> enumList = new ArrayList<>();
                            for (IEnum iEnum : iEnums) {
                                EnumDTO enumDTO = new EnumDTO();
                                enumDTO.setValue(iEnum.getValue());
                                enumDTO.setMsg(iEnum.getMsg());
                                enumList.add(enumDTO);
                            }
                            ENUM_MAP.put(cls.getSimpleName(), enumList);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
